package com.supers.sign.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author shiyuan
 * @date 2019/8/24
 */
@Slf4j
@Controller
@RequestMapping("UDID")
public class UDIDController {

    @PostMapping("received")
    public void receivedUDID(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("UTF-8");
            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
            StringBuilder stb = new StringBuilder();
            String line ;
            boolean isUDID = false;
            String UDID = null;
            while ((line = in.readLine()) != null) {
                stb.append(line);
                if(isUDID && StringUtils.isEmpty(UDID)){
                    UDID = line.replaceAll("</\\S+","")
                            .replaceAll("\\S+>","");
                }
                if(line.indexOf("UDID") > -1){
                    isUDID = true;
                }
            }
            log.info("收到xml数据:{}",stb.toString());
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            response.setHeader("Location","http://39.100.235.101/index.html?UDID="+UDID);
        }catch (Exception e){
            log.error("接收UDID出错",e);
        }

    }

    @GetMapping("download")
    public void downloadConfig(HttpServletRequest req,HttpServletResponse resp) throws FileNotFoundException {
        //第一步：设置响应类型
        resp.setHeader("Content-Disposition", "attachment;filename=super-sign.mobileconfig");
        resp.setContentType("application/force-download");//应用程序强制下载
        //第二读取文件
        OutputStream out = null;
        InputStream in = this.getClass().getResourceAsStream("/super-sign.mobileconfig");
        try {
            out = resp.getOutputStream();
            resp.setContentLength(in.available());
            IOUtils.copy(in, out);
        } catch (Exception ex) {
            log.error("下载出错",ex);
        }finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                log.error("关闭流出错",e);
            }
        }

    }

}
